package com.moon.es;

import com.moon.dao.TAuctionMapper;
import com.moon.dao.TProductMapper;
import com.moon.dto.EsProduct;
import com.moon.dto.ProductVo;
import com.moon.entity.TAuction;
import com.moon.entity.TProduct;
import com.moon.utils.ProductUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("esProduct")
public class EsProductDataWriter implements EsDataWriter{

    @Autowired
    TProductMapper productMapper;

    @Autowired
    TAuctionMapper auctionMapper;

    @Autowired
    EsProductRepository esProductRepository;

    @Override
    public void dataWrite() {
        //将mysql中的数据全部读取出来,然后写入到es中
        List<TProduct> all = productMapper.selectAll();

        List<ProductVo> voList = new ArrayList<>();

        for (TProduct product : all) {
            TAuction auction = new TAuction();
            auction.setProductId(product.getId());
            //竞拍室集合
            List<TAuction> auctionList = auctionMapper.select(auction);
            ProductVo vo = ProductUtils.getList(product);
            vo.setAuctionList(auctionList);
            //进行中的竞拍
            if (auctionList!=null){
                for (TAuction tAuction : auctionList) {
                    if (tAuction.getStatus() == 1) {
                        vo.setAuction(tAuction);
                    }
                }
            }
            voList.add(vo);
        }

        List<EsProduct> esProductList = voList.stream().map(product -> {
            EsProduct esProduct = new EsProduct();

            esProduct.setId(product.getId());
            esProduct.setSellerId(product.getSellerId());
            esProduct.setProductName(product.getProductName());
            esProduct.setProductDetail(product.getProductDetail());
            esProduct.setStatus(product.getStatus());
            esProduct.setProductImgList(product.getProductImgList());
            esProduct.setAuctionList(product.getAuctionList());
            esProduct.setAuction(product.getAuction());

            return esProduct;
        }).collect(Collectors.toList());
        esProductRepository.saveAll(esProductList);

    }

}
